<?php
/**
 * 应用公共文件
 */

/**
 * 格式化前端传来的带逗号的参数
 * @param $str
 * @param int $returnArr
 * @return array|string
 */
function formatParamString($str, $returnArr = 1)
{
    $arr = array_unique(array_filter(explode(',', $str)));
    return $returnArr ? $arr : implode(',', $arr);
}

/**
 * 当前日期
 */
function currentDate()
{
    return date('Y-m-d');
}

/**
 * 正负数相互转换（支持小数）
 * @param int $number
 * @return float|int
 */
function plus_minus_conversion($number = 0)
{
    return $number > 0 ? -1 * $number : abs($number);
}

/**
 * 获取毫秒时间
 * @return float
 */
function microsecond()
{
    $t = explode(" ", microtime());
    $microsecond = round(round($t[1] . substr($t[0], 2, 3)));
    return $microsecond;
}

/**
 * 清除指定缓存
 * @param $key
 */
function clearCacheByKey($key)
{
    cache($key, null);
}

/**
 * PHP stdClass Object转array
 * @param $object
 * @return mixed
 */
function object2array(&$object)
{
    $object = json_decode(json_encode($object), true);
    return $object;
}

/**
 * 返回成功状态码和消息
 * @param string $msg
 * @param int $status
 * @return array
 */
function backSuccess($res = [], $msg = 'OK', $status = 1)
{
    $data = ['status' => $status, 'msg' => $msg, 'res' => $res];
    exit(json_encode($data, JSON_UNESCAPED_UNICODE));
}

/**
 * 返回错误状态码和消息
 * @param string $msg
 * @param int $status
 * @return array
 */
function backError($msg = 'FAIL', $status = 0, $res = [])
{
    $data = ['status' => $status, 'msg' => $msg, 'res' => $res];
    exit(json_encode($data, JSON_UNESCAPED_UNICODE));
}

/**
 * AJAX返回
 * @param array $data
 * @param string $type
 */
function ajaxReturn($data = ['status' => 1, 'msg' => 'ok'], $type = 'json')
{
    exit(json_encode($data, JSON_UNESCAPED_UNICODE));
}

/**
 * 管理员登录记录
 * @param $log_url
 * @param $log_info
 * @param $log_type
 */
function adminLog($log_info, $log_type = 0)
{
    $add['addTime'] = time();
    $add['adminID'] = session('adminInfo')['id'];
    $add['logInfo'] = $log_info;
    $add['logIP'] = getIP();
    $add['logUrl'] = \think\Request::instance()->url();
    $add['logType'] = $log_type;
    $add['sql'] = \app\common\model\XkAdmin::getLastSql();
    M('admin_log')->add($add);
}

/**
 * 获取IP
 * @return array|false|string
 */
function getIP()
{
    if (getenv("HTTP_CLIENT_IP")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else {
            if (getenv("REMOTE_ADDR")) {
                $ip = getenv("REMOTE_ADDR");
            } else {
                $ip = "Unknow";
            }
        }
    }

    if (preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/',
        $ip)) {
        return $ip;
    } else {
        return '';
    }
}

/**
 * 删除数据库记录--软删除
 * @param $table表名
 * @param $primaryID主键ID名称
 * @param $ids删除的id
 * @param string $name软删除字段名称
 * @param int $value设置软删除字段的值
 * @return array
 */
function deleteRecords($table, $primaryID, $ids, $name = 'isDel', $value = 1)
{
    $str = rtrim($ids, ',');
    //  id 数组
    $arr = array_unique(array_filter(explode(',', $str)));
    // 启动事务
    \think\Db::startTrans();
    try {
        if (M($table)->where([$primaryID => ['in', $arr]])->select()) {
            $res = M($table)->where([$primaryID => ['in', $arr]])->save([$name => $value]);
            if (!$res) throw new \think\Exception('删除失败1');
        }

        if (in_array($table, ['admin_role'])) {
            switch ($table) {
                case 'admin_role':
                    //  查看当前角色下是否有管理员
                    if (\app\common\model\XkAdmin::where(['roleID' => ['in', $arr]])->count()) {
                        //  删除对应角色下面的管理员
                        $res = \app\common\model\XkAdmin::where(['roleID' => ['in', $arr]])->save(['isDel' => 1, 'updateTime' => time()]);
                        if (!$res) throw new \think\Exception('删除失败2');
                    }
                    break;
            }
        }

        // 提交事务
        \think\Db::commit();
        $backData = ['status' => 1, 'msg' => '删除成功'];
    } catch (\Exception $e) {
        // 回滚事务
        \think\Db::rollback();
        $backData = ['status' => 0, 'msg' => $e->getMessage()];
    }
    return $backData;

}

/**
 * 字符串截取并且超出显示省略号
 * @param $text
 * @param $length
 * @return string
 */
function subtext($text, $length)
{
    return mb_strlen($text, 'utf8') > $length ? mb_substr($text, 0, $length, 'utf8') . '...' : $text;
}

/**
 * 正则判断手机号/邮箱
 * 手机号/邮箱
 * type 0->手机 1->邮箱
 */
function isLegalForm($data, $type = 0)
{
    if (empty($data)) {
        return ['status' => 0, 'msg' => '传入数据不能为空'];
    }
    switch ($type) {
        case 0:
            if (!preg_match("/^1[3456789]\d{9}$/", $data)) {
                return ['status' => 0, 'msg' => '手机号码格式不正确'];
            }
            break;
        case 1:
            if (!filter_var($data, FILTER_VALIDATE_EMAIL)) {
                return ['status' => 0, 'msg' => '邮箱格式不正确'];
            }
            break;
    }
    return ['status' => 1, 'msg' => 'ok'];
}